<template>
    <div class="info-com">
        <el-tabs v-model="tabActive" type="card" :closable="areaList.length > 1" @tab-remove="removeTab" @tab-click="changeTab">
            <el-tab-pane v-for="(el, index) in areaList" :key="el.id" :label="el.drawLayerName" :name="el.id"></el-tab-pane>
        </el-tabs>

        <el-button v-show="areaList.length < 2" class="add-btn" type="text" icon="el-icon-plus" @click="add"></el-button>

        <el-form ref="form" :model="form" :rules="rules" label-width="130px" size="small" label-suffix="：">
            <el-form-item class="type-item" label="灾害落区类型" prop="type">
                <el-radio-group class="type" v-model="form.type" @input="changeType">
                    <el-radio v-for="el in typeList" :key="el.value" :label="el.value" :disabled="el.disabled">
                        <span :class="[el.icon]"></span>
                        <span>{{ el.label }}</span>
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
                <el-col :span="16">
                    <el-date-picker type="date" placeholder="请选择" v-model="form.startTime" value-format="yyyy-MM-dd" :clearable="false" style="width: 90%" @change="changeTime"></el-date-picker>
                </el-col>
                <el-col :span="8">
                    <el-select v-model="form.startHour" placeholder="请选择" @change="changeTime">
                        <el-option v-for="item in hourList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-col>
            </el-form-item>
            <el-form-item label="预报时效" prop="ybAging">
                <el-radio-group v-model="form.ybAging" @input="changeTime">
                    <el-radio-button v-for="el in ybAgingList" :key="el.value" :label="el.label">{{ el.name }}</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
                <el-col :span="16">
                    <el-date-picker type="date" placeholder="请选择" v-model="form.endTime" value-format="yyyy-MM-dd" disabled :clearable="false" style="width: 90%"></el-date-picker>
                </el-col>
                <el-col :span="8">
                    <el-select v-model="form.endHour" placeholder="请选择" disabled>
                        <el-option v-for="item in hourList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-col>
            </el-form-item>
            <el-form-item label="制作人" prop="producer">
                <el-input v-model="form.producer"></el-input>
            </el-form-item>
            <el-form-item label="" label-width="0" prop="types">
                <div class="type-table">
                    <div class="table-header">
                        <div class="item">类型</div>
                        <div class="item">短时强降水</div>
                        <div class="item">雷暴大风</div>
                        <div class="item">冰雹</div>
                    </div>
                    <div class="table-body">
                        <div class="item">极端性</div>
                        <el-input v-model="form.rainMsg" placeholder=""></el-input>
                        <el-input v-model="form.windMsg" placeholder=""></el-input>
                        <el-input v-model="form.hailMsg" placeholder=""></el-input>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="影响区域" prop="areaContent">
                <el-input type="textarea" :rows="4" v-model="form.areaContent"></el-input>
            </el-form-item>
            <el-form-item label="预报结论" prop="ybResult">
                <el-input type="textarea" :rows="6" v-model="form.ybResult"></el-input>
            </el-form-item>
        </el-form>

        <div class="btn-group">
            <el-button size="small" @click="next">下一步</el-button>
        </div>

        <div style="display: none;">{{ areaContent }}</div>
    </div>
</template>

<script>
import { mapGetters } from 'vuex';
import TabCom from './TabCom.vue';
import API from '@/api/home';

export default {
    name: 'InfoCom',
    components: {
        TabCom,
    },
    props: {
        mapGis: {
            type: Object,
            default: () => {},
        },
        imgFileAreas1: {
            type: Array,
            default: () => [],
        },
        imgFileAreas2: {
            type: Array,
            default: () => [],
        },
    },
    computed: {
        ...mapGetters([
            'getMapId',
            'getDrawLayerId',
        ]),
        areaContent() {
            return [...this.imgFileAreas1, ...this.imgFileAreas2].filter((el, index, arr) => arr.findIndex(item => item.areacode === el.areacode) === index);
        }
    },
    watch: {
        imgFileAreas1: {
            handler(newVal, oldVal) {
                this.getForecastResult();
            },
            deep: true
        },
        imgFileAreas2: {
            handler(newVal, oldVal) {
                this.getForecastResult();
            },
            deep: true
        },
        areaContent: {
            handler(newVal, oldVal) {
                this.form.areaContent = newVal.map(el => el.name).join(',');
                this.getForecastResult();
            },
            deep: true
        }
    },
    data() {
        return {
            areaList: [],
            tabActive: 'tab_1',
            form: {
                type: '',
                startTime: this.$dayjs().format('YYYY-MM-DD'),
                startHour: '08',
                ybAging: '1',
                endTime: this.$dayjs().add(1, 'hour').format('YYYY-MM-DD'),
                endHour: '09',
                producer: '',
                rainMsg: '20mm',
                windMsg: '8级',
                hailMsg: '',
                areaContent: '',
                ybResult: '',
            },
            rules: {
                producer: [
                    { required: true, message: '请输入制作人', trigger: 'blur' }
                ],
            },
            typeList: [
                {label: '强降水', value: 'RAT', disabled: false, icon: 'rain'}, 
                {label: '雷雨大风', value: 'SMG', disabled: false, icon: 'wind'}, 
            ],
            hourList: [
                {label: '00时', value: '00'},
                {label: '01时', value: '01'},
                {label: '02时', value: '02'},
                {label: '03时', value: '03'},
                {label: '04时', value: '04'},
                {label: '05时', value: '05'},
                {label: '06时', value: '06'},
                {label: '08时', value: '08'},
                {label: '09时', value: '09'},
                {label: '10时', value: '10'},
                {label: '11时', value: '11'},
                {label: '12时', value: '12'},
                {label: '13时', value: '13'},
                {label: '14时', value: '14'},
                {label: '15时', value: '15'},
                {label: '16时', value: '16'},
                {label: '17时', value: '17'},
                {label: '18时', value: '18'},
                {label: '19时', value: '19'},
                {label: '20时', value: '20'},
                {label: '21时', value: '21'},
                {label: '22时', value: '22'},
                {label: '23时', value: '23'},
            ],
            ybAgingList: [
                {name: '1h', label: '1'},
                {name: '2h', label: '2'},
                {name: '3h', label: '3'},
                {name: '6h', label: '6'},
                {name: '12h', label: '12'},
            ],
            userId: '',
            areaCodes: [],
            count: 0,
            timer: null,
        }
    },
    mounted() {
        this.userId = this.$route.query.userId || '2';
        let now = this.$dayjs();
        let startHour = now.minute() >= 30 ? now.startOf('hour').hour() : now.subtract(1, 'hour').hour();
        this.form.startHour = `${startHour}`.padStart(2, '0');
        this.findUserName();
        this.init();
        this.$once('hook:beforeDestroy', () => clearInterval(this.timer));
    },
    methods: {
        async init() {
            try {
                let res = await API.init({
                    bjTime: this.$dayjs(`${this.form.startTime} ${this.form.startHour}`, 'YYYY-MM-DD HH').format('YYYY-MM-DD HH:00:00')
                });

                if (res.data.code === 200 && res.data.data) {
                    if (Object.values(res.data.data).some(el => el)) {
                        this.timer = setInterval(() => {
                            console.log('setInterval======>');
                            if (GLMap?.geometryData?.areaconfig) {
                                clearInterval(this.timer);
                                Object.keys(res.data.data).forEach(el => {
                                    if (res.data.data[el]) {
                                        let areaCodes = res.data.data[el].split(',');
                                        this.form.type = el === 'RAT' ? 'SMG' : 'RAT';
                                        this.add(areaCodes);
                                    }
                                });
                            }
                        }, 100);
                    } else {
                        this.add();
                    }
                } else {
                    this.add();
                    this.$message.error(res.data.msg);
                }
            } catch (error) {
                this.add();
                console.log('error======>', error);
                this.$message.error(error);
            }
        },
        changeType(val) {
            let item = this.areaList.find(el => el.id === this.tabActive);
            item.type = val;
            if (val === 'RAT') {
                item.strokeStyle = 'rgba(158, 255, 159, 1)';
                item.fillStyle = 'rgba(49, 114, 50, 1)';
            } else {
                item.strokeStyle = 'rgba(209, 106, 15, 1)';
                item.fillStyle = 'rgba(255, 204, 0, 1)';
            }

            let areaCodes = [];
            if (val === 'RAT') {
                areaCodes = JSON.parse(JSON.stringify(this.imgFileAreas2));
            } else {
                areaCodes = JSON.parse(JSON.stringify(this.imgFileAreas1));
            }

            this.$emit('changeType', item, areaCodes);
        },
        changeTime(val) {
            let fullTime = this.$dayjs(`${this.form.startTime} ${this.form.startHour}`, 'YYYY-MM-DD HH').add(this.form.ybAging, 'hour');
            this.form.endTime = fullTime.format('YYYY-MM-DD');
            this.form.endHour = fullTime.format('HH');
            this.getForecastResult();
        },
        add(areacodes) {
            if (this.areaList.length === 2) return;
            this.form.type = this.form.type === 'RAT' ? 'SMG' : 'RAT';
            this.count++;
            let item = {
                id: `tab_${this.count}`,
                type: this.form.type,
                drawLayerId: `drawLayerId_${this.count}`,
                drawLayerName: `落区${this.count}`,
                strokeStyle: this.form.type === 'RAT' ? 'rgba(158, 255, 159, 1)' : 'rgba(209, 106, 15, 1)',
                fillStyle: this.form.type === 'RAT' ? 'rgba(49, 114, 50, 1)' : 'rgba(255, 204, 0, 1)',
                fallZoneLayerId: `fallZoneLayerId_${this.count}`,
            };
            this.areaList.push(item);
            this.areaList.length === 2 && (this.typeList.forEach(el => el.disabled = true));
            this.tabActive = `tab_${this.areaList.length}`;
            this.$emit('changeTab', item);
            areacodes && this.$emit('initInfoCom', areacodes);
        },
        removeTab(id) {
            if (this.areaList.length === 1) return;
            let index = this.areaList.findIndex(el => el.id === id);
            let item = this.areaList.find(el => el.id === id);
            this.areaList.splice(index, 1);
            GIS?.LayerControll?.clearLayer(this.getMapId, [item.drawLayerId,item.fallZoneLayerId]);

            if (index === 0) {
                this.tabActive = this.areaList[0].id;
            } else {
                this.tabActive = this.areaList[index - 1].id;
            }
            
            this.form.type = item.type === 'RAT' ? 'SMG' : 'RAT';
            this.typeList.forEach(el => el.disabled = false);
            this.$emit('removeTab', item, this.areaList[0]);
        },
        changeTab(tab) {
            let item = this.areaList.find(el => el.id === tab.name);
            this.form.type = item.type;
            this.$emit('changeTab', item);
        },
        async next() {
            try {
                let res = await API.getWordUrl({
                    bjTime: this.$dayjs(`${this.form.startTime} ${this.form.startHour}`, 'YYYY-MM-DD HH').format('YYYY-MM-DD HH:mm:ss'),
                    ybAging: this.form.ybAging,
                    rainMsg: this.form.rainMsg,
                    windMsg: this.form.windMsg,
                    hailMsg: this.form.hailMsg,
                    userId: this.userId,
                    imgFileAreas1: this.imgFileAreas1.map(el => el.areacode).join(','),
                    imgFileAreas2: this.imgFileAreas2.map(el => el.areacode).join(','),
                    areaContent: this.form.areaContent,
                    ybResult: this.form.ybResult,
                });

                if (res.data.code === 200 && res.data.data) {
                    this.$emit('next', res.data.data);
                } else {
                    this.$message.error(res.data.msg);
                }
            } catch (error) {
                console.log('error======>', error);
                this.$message.error(error);
            }
            
        },
        async findUserName() {
            try {
                let res = await API.findUserName({
                    userId: this.userId,
                });
                if (res.data.code === 200 && res.data.data) {
                    this.form.producer = res.data.data;
                } else {
                    this.$message.error(res.data.msg);
                }
            } catch (error) {
                console.log('error======>', error);
                this.$message.error(error);
            }
            
        },
        getForecastResult() {
            this.form.ybResult = `预计强对流系统未来${this.form.ybAging}小时将在${this.imgFileAreas1.length ? this.imgFileAreas1.map(el => el.name).join(',') + '地区产生' + this.form.rainMsg + '强降水；' : ''}${this.imgFileAreas2.length ? this.imgFileAreas2.map(el => el.name).join(',') + '地区产生' + this.form.windMsg + '雷暴大风；' : ''}`;
        }
    }
}
</script>

<style lang="less" scoped>
.info-com {
    position: relative;
    padding: 20px;
    width: 100%;
    height: 100%;
    background-color: #ffffff;

    .add-btn {
        position: absolute;
        right: 30px;
        top: 20px;
    }

    /deep/ .el-form {
        .el-form-item {
            &.type-item {
                border-bottom: 1px solid #e4e7ed;
                margin-bottom: 30px;
                padding: 20px 0 30px 0;
            }

            .type {
                .rain {
                    display: inline-block;
                    margin-right: 5px;
                    width: 16px;
                    height: 16px;
                    vertical-align: middle;
                    background: url('@/assets/images/toolbar/rain.png') no-repeat center center / 100% 100%;
                }

                .wind {
                    display: inline-block;
                    margin-right: 5px;
                    width: 16px;
                    height: 16px;
                    vertical-align: middle;
                    background: url('@/assets/images/toolbar/wind.png') no-repeat center center / 100% 100%;
                }
            }

            .type-table {
                color: #606266;
                
                .table-header, 
                .table-body {
                    display: flex;
                    align-items: center;
                    height: 32px;
                    border: 1px solid #b9b9b9;
                    
                    .item {
                        flex: 1;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        border-right: 1px solid #b9b9b9;

                        &:last-child {
                            border-right: none;
                        }
                    }

                    .el-input {
                        flex: 1;

                        .el-input__inner {
                            border-radius: 0;
                            border-color: transparent;
                            border-right: 1px solid #b9b9b9;
                            background-color: transparent;
                        }

                        &:last-child {
                            .el-input__inner {
                                border-right: none;
                            }
                        }
                    }
                }

                .table-body {
                    border-top: none;
                }
            }
        }
    }

    .btn-group {
        position: absolute;
        right: 20px;
        bottom: 20px;
        display: flex;
        justify-content: flex-end;
    }
}
</style>
